package com.ycsj.goldmedalnewconcept.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.crypto.spec.GCMParameterSpec;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.Bimp;
import com.ycsj.goldmedalnewconcept.utils.FileUtils;
import com.ycsj.goldmedalnewconcept.utils.ImageItem;
import com.ycsj.goldmedalnewconcept.utils.PublicWay;
import com.ycsj.goldmedalnewconcept.utils.Res;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;

//发布公告
public class GonggaoCreatActivity extends Activity implements OnClickListener {

	private ImageView iv_back;
	private GridView noScrollgridview;
	private GridAdapter adapter;
	private View parentView;
	private PopupWindow pop = null;
	private LinearLayout ll_popup;
	public static Bitmap bimap;

	private EditText et_theme;
	private EditText et_content;
	private TextView tv_preview;
	private TextView tv_upload;
	
	private LinearLayout ll_loading;
	private HttpUtils httpUtils;
	private RequestParams params;
	private String theme;
	private String content;
	private String url;
	private File f;
	private String account;
	private String role;
	public static String SDPATH = Environment.getExternalStorageDirectory()
			+ "/Photo_LJ/";
	
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		Res.init(this);
		bimap = BitmapFactory.decodeResource(getResources(),
				R.drawable.icon_addpic_unfocused);

		PublicWay.activityList.add(this);
		parentView = getLayoutInflater().inflate(
				R.layout.activity_gonggaocreat, null);
		setContentView(parentView);
		account = SPUtil.getString(this, "account", "");
		role = SPUtil.getString(this, "role", "");
		Init();

	}

	private void Init() {
		iv_back = (ImageView) findViewById(R.id.iv_back);
		et_theme = (EditText) findViewById(R.id.et_theme);
		et_content = (EditText) findViewById(R.id.et_content);
		tv_preview = (TextView) findViewById(R.id.tv_preview); // 预览
		tv_upload = (TextView) findViewById(R.id.tv_upload); // 发送

		iv_back.setOnClickListener(this);
		tv_preview.setOnClickListener(this);
		tv_upload.setOnClickListener(this);

		pop = new PopupWindow(GonggaoCreatActivity.this);

		View view = getLayoutInflater().inflate(R.layout.item_popupwindows,
				null);

		ll_popup = (LinearLayout) view.findViewById(R.id.ll_popup);
		ll_loading = (LinearLayout)findViewById(R.id.ll_loading);

		pop.setWidth(LayoutParams.MATCH_PARENT);
		pop.setHeight(LayoutParams.WRAP_CONTENT);
		pop.setBackgroundDrawable(new BitmapDrawable());
		pop.setFocusable(true);
		pop.setOutsideTouchable(true);
		pop.setContentView(view);

		RelativeLayout parent = (RelativeLayout) view.findViewById(R.id.parent);
		Button bt1 = (Button) view.findViewById(R.id.item_popupwindows_camera);
		Button bt2 = (Button) view.findViewById(R.id.item_popupwindows_Photo);
		Button bt3 = (Button) view.findViewById(R.id.item_popupwindows_cancel);
		parent.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		
		bt1.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				photo();
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt2.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(GonggaoCreatActivity.this,
						AlbumActivity.class);
				startActivity(intent);
				overridePendingTransition(R.anim.activity_translate_in,
						R.anim.activity_translate_out);
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});
		bt3.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				pop.dismiss();
				ll_popup.clearAnimation();
			}
		});

		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					Log.i("ddddddd", "----------");
					ll_popup.startAnimation(AnimationUtils.loadAnimation(
							GonggaoCreatActivity.this,
							R.anim.activity_translate_in));
					pop.showAtLocation(parentView, Gravity.BOTTOM, 0, 0);
				} else {
					Intent intent = new Intent(GonggaoCreatActivity.this,
							GalleryActivity.class);
					intent.putExtra("position", "1");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	@SuppressLint("HandlerLeak")
	public class GridAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private int selectedPosition = -1;
		private boolean shape;

		public boolean isShape() {
			return shape;
		}

		public void setShape(boolean shape) {
			this.shape = shape;
		}

		public GridAdapter(Context context) {
			inflater = LayoutInflater.from(context);
		}

		public void update() {
			loading();
		}

		public int getCount() {
			if (Bimp.tempSelectBitmap.size() == 9) {
				return 9;
			}
			return (Bimp.tempSelectBitmap.size() + 1);
		}

		public Object getItem(int arg0) {
			return null;
		}

		public long getItemId(int arg0) {
			return 0;
		}

		public void setSelectedPosition(int position) {
			selectedPosition = position;
		}

		public int getSelectedPosition() {
			return selectedPosition;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.item_published_grida,
						parent, false);
				holder = new ViewHolder();
				holder.image = (ImageView) convertView
						.findViewById(R.id.item_grida_image);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			if (position == Bimp.tempSelectBitmap.size()) {
				holder.image.setImageBitmap(BitmapFactory.decodeResource(
						getResources(), R.drawable.icon_addpic_unfocused));
				if (position == 9) {
					holder.image.setVisibility(View.GONE);
				}
			} else {
				holder.image.setImageBitmap(Bimp.tempSelectBitmap.get(position)
						.getBitmap());
			}

			return convertView;
		}

		public class ViewHolder {
			public ImageView image;
		}

		Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case 1:
					adapter.notifyDataSetChanged();
					break;
				}
				super.handleMessage(msg);
			}
		};

		public void loading() {
			new Thread(new Runnable() {
				public void run() {
					while (true) {
						if (Bimp.max == Bimp.tempSelectBitmap.size()) {
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
							break;
						} else {
							Bimp.max += 1;
							Message message = new Message();
							message.what = 1;
							handler.sendMessage(message);
						}
					}
				}
			}).start();
		}
	}

	public String getString(String s) {
		String path = null;
		if (s == null)
			return "";
		for (int i = s.length() - 1; i > 0; i++) {
			s.charAt(i);
		}
		return path;
	}

	protected void onRestart() {
		adapter.update();
		super.onRestart();
	}

	private static final int TAKE_PICTURE = 0x000001;

	public void photo() {
		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(openCameraIntent, TAKE_PICTURE);
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case TAKE_PICTURE:
			if (Bimp.tempSelectBitmap.size() < 9 && resultCode == RESULT_OK) {

				String fileName = String.valueOf(System.currentTimeMillis());
				Bitmap bm = (Bitmap) data.getExtras().get("data");
				FileUtils.saveBitmap(bm, fileName);
				
				ImageItem takePhoto = new ImageItem();
				takePhoto.setBitmap(bm);
				takePhoto.setImagePath(Environment.getExternalStorageDirectory()
						+ "/Photo_LJ/"+fileName+ ".png");
				Bimp.tempSelectBitmap.add(takePhoto);
			}
			break;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			for (int i = 0; i < PublicWay.activityList.size(); i++) {
//				if (null != PublicWay.activityList.get(i)) {
//					PublicWay.activityList.get(i).finish();
//				}
//			}
			finish();
		}
		return true;
	}
	
	@Override
	protected void onDestroy() {
		for (int i = 0; i < PublicWay.activityList.size(); i++) {
			if (null != PublicWay.activityList.get(i)) {
				PublicWay.activityList.get(i).finish();
			}
		}
		
		bimap = null;
		System.gc();
		
		Bimp.tempSelectBitmap.clear();
		Bimp.max = 0;
		Intent intent = new Intent("data.broadcast.action");  
        sendBroadcast(intent);  
        
		super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.tv_preview:
			//预览
			theme = et_theme.getText().toString().trim();
			content = et_content.getText().toString();
			if ("".equals(theme)) {
				Toast.makeText(this, "请输入公告主题", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			
			if ("".equals(content)) {
				Toast.makeText(this, "请输入公告内容", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			Intent intent = new Intent(GonggaoCreatActivity.this, GonggaoPreviewActivity.class);
			intent.putExtra("theme", theme);
			intent.putExtra("content", content);
			startActivity(intent);
			break;
		case R.id.tv_upload:
			//上传
			theme = et_theme.getText().toString().trim();
			content = et_content.getText().toString();

//			for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
//				Log.e("test","imagePath"+ Bimp.tempSelectBitmap.get(i).imagePath);
//			}
			
			if ("".equals(theme)) {
				Toast.makeText(this, "请输入公告主题", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			
			if ("".equals(content)) {
				Toast.makeText(this, "请输入公告内容", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			
			tv_upload.setClickable(false);
			ll_loading.setVisibility(ll_loading.VISIBLE);
			httpUtils = new HttpUtils();
			url = Constant.SERVER_LOC + "ManageMsg";
			params = new RequestParams();
			params.addBodyParameter("type","28");
			params.addBodyParameter("c", account);
			params.addBodyParameter("role",role);
			params.addBodyParameter("tag", theme);
			params.addBodyParameter("userclass", "");
			params.addBodyParameter("content", content);
			params.addBodyParameter("status","0");
//http://192.168.0.198:8888/ycsj_platform/ManageMsg?type=23&c=18271261779&role=2&teacherid=18271261779&vtype=0
			
			for (int i = 0; i < Bimp.tempSelectBitmap.size(); i++) {
				String name = String.valueOf(System.currentTimeMillis())+ i +".png";
				try {
					f = new File(SDPATH, name); 
					if (f.exists()) {
						f.delete();
					}
					FileOutputStream out = new FileOutputStream(f);
					Bimp.tempSelectBitmap.get(i).getBitmap().compress(Bitmap.CompressFormat.PNG, 20, out);
					out.flush();
					out.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				params.addBodyParameter(name, f, "image/png");
			}
			 httpUtils.send(HttpMethod.POST, url, params,
			 callBackHeadimg);
			break;
		}
		
	}
	private RequestCallBack<String> callBackHeadimg = new RequestCallBack<String>() {

		@Override
		public void onSuccess(ResponseInfo<String> responseInfo) {

			String json = responseInfo.result;
			Log.e("test", json);
			ll_loading.setVisibility(ll_loading.GONE);
			
			
			Intent broadCastIntent = new Intent();
			broadCastIntent.setAction(GonggaoActivity.BROADCAST_ACTION1);
			sendBroadcast(broadCastIntent);
			
			
			Toast.makeText(getBaseContext(), "上传成功！", 1).show();
			Intent intent = new Intent(GonggaoCreatActivity.this, GonggaoActivity.class);
			startActivity(intent);
			finish();
		}

		@Override
		public void onFailure(HttpException error, String msg) {
			ll_loading.setVisibility(ll_loading.GONE);
			Toast.makeText(getBaseContext(), "上传失败，请重新上传", 0).show();
			tv_upload.setClickable(true);
		}
	};
}
